package com.yjb.gateway.controller;


import com.alibaba.fastjson.JSON;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Map;

@RestController
@RequestMapping("/gateway")
public class AuthController {
/*    @Value("${security.oauth2.client.client-id}")
    private String client;
    @Value("${security.oauth2.client.client-secret}")
    private String secret;
    @Value("${security.oauth2.client.access-token-uri}")
    private String accessTokenUri;*/

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/")
    public String index() {
        return "index";
    }
/*
    @RequestMapping("/redirect") //获取授权码时的回调地址，使用获得的授权码获取access_token
    public Map get(@RequestParam(value = "code") String code) {
        try {
            String authorization = client + ":" + secret;
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(accessTokenUri);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            String encoding = DatatypeConverter.printBase64Binary(authorization.getBytes("UTF-8"));
            httpPost.setHeader("Authorization", "Basic " + encoding);
            ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<>();
            nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
            nameValuePairs.add(new BasicNameValuePair("code", code));
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8);
            httpPost.setEntity(formEntity);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String s = EntityUtils.toString(entity);
            AuthDto authDto = JSON.parseObject(s, AuthDto.class);
            System.out.println(authDto);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }*/
}
